package com.micro.center.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.micro.center.dto.AppDto;
import com.micro.center.entity.SysAppEntity;
import com.micro.center.mapper.SysAppMapper;
import com.micro.common.constant.Constant;
import com.micro.common.constant.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author pan.shun
 * @since 2022/7/12 09:38
 */
@Slf4j
@Service
public class SysAppService extends ServiceImpl<SysAppMapper, SysAppEntity> {

    public R getList(AppDto appDto) {
        LambdaQueryWrapper<SysAppEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(SysAppEntity::getCreateTime);
        if (!StringUtils.isEmpty(appDto.getAppName())) {
            queryWrapper.like(SysAppEntity::getAppName, appDto.getAppName());
        }
        if (!StringUtils.isEmpty(appDto.getStatus())) {
            queryWrapper.eq(SysAppEntity::getStatus, appDto.getStatus());
        }
        List<SysAppEntity> list = this.list(queryWrapper);
        return R.success(list);
    }

    public R delete(String id) {
        this.removeById(id);
        return R.success();
    }

    public R addOrUpdate(SysAppEntity sysAppEntity) {
        if (StringUtils.isEmpty(sysAppEntity.getId())) {
            this.save(sysAppEntity);
        } else {
            this.updateById(sysAppEntity);
        }
        return R.success();
    }

    public R getUrlByAppId(String appId) {
        LambdaQueryWrapper<SysAppEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(SysAppEntity::getRedirectUrl, SysAppEntity::getStatus);
        queryWrapper.eq(SysAppEntity::getId, appId);
        SysAppEntity appEntity = this.getOne(queryWrapper);
        if (null != appEntity) {
            if (appEntity.getStatus().equals(Constant.APP_STATUS.NORMAL)) {
                return R.success(appEntity.getRedirectUrl());
            } else {
                return R.success();
            }
        } else {
            return R.success();
        }
    }
}
